﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using MethodWorx.CMS.Administration;
using MethodWorx.CMS.Configuration;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.Providers;

namespace MethodWorx.CMS.Web.Mvc
{
    public class PluginModule : IHttpModule
    {
        #region IHttpModule Members

        private CmsRequestContext pluginRequestContext = new CmsRequestContext();
        private PluginService pluginService;
        private PluginFactory plugins;

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication context)
        {
            // Below is an example of how you can handle LogRequest event and provide 
            // custom logging implementation for it
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);

            //
            //  ok, time to map the request via the CMS
            //  first things first, grab hold of the provider
            ICmsDataProvider provider = WebConfiguration.Instance.Provider;

            pluginService = new PluginService(provider.GetUnitOfWorkFactory(), provider.GetService<IPluginUserDataRepository>(), new PluginRepository(provider));
            plugins = new PluginFactory(provider.GetService<IApplicationSettingsRepository>(), new PluginRepository(provider));
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            CmsRequestContext.Current.Dispose();
        }

        void context_BeginRequest(object sender, EventArgs e)
        {



            bool processed = this.ProcessWithPlugins(plugins);

            if(processed)
                HttpContext.Current.Response.End();
        }

        private bool ProcessWithPlugins(PluginFactory plugins)
        {
            bool processed = false;
            foreach (SafePlugin plugin in plugins.GetRequestPlugins())
            {
                //
                //  ok, process
                processed = plugin.Invoke<IRequestPlugin, bool>(p => p.ProcessRequest(new HttpContextWrapper(HttpContext.Current)));
                if (processed)
                    break;
            }

            return processed;
        }

        #endregion
    }
}
